package com.gxp.web.controller;

import com.gxp.common.annotation.Audit;
import com.gxp.common.config.GxPConfig;
import com.gxp.common.config.ServerConfig;
import com.gxp.common.core.controller.BaseController;
import com.gxp.common.core.domain.AjaxResult;
import com.gxp.common.core.page.TableDataInfo;
import com.gxp.common.enums.BusinessAction;
import com.gxp.common.enums.BusinessTitle;
import com.gxp.common.utils.file.FileUploadUtils;
import com.gxp.system.domain.ZknjExpTemplate;
import com.gxp.system.service.IZkInstrumentService;
import com.gxp.system.service.IZknjExpTemplateService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.stream.Collectors;

/**
 * 模板Controller
 * 
 * @author zh
 * @date 2024-07-22
 */
@Controller
@RequestMapping("/system/template")
public class ZknjExpTemplateController extends BaseController
{
    private String prefix = "system/instrument/template";

    @Autowired
    private IZknjExpTemplateService zknjExpTemplateService;
    @Autowired
    private IZkInstrumentService instrumentService;
    @Autowired
    private ServerConfig serverConfig;

    /**
     * 多文件间隔
     */
    private static final String FILE_DELIMETER = ",";

    @GetMapping()
    public String template()
    {
        return prefix + "/template";
    }

    /**
     * 查询模板列表
     */
    @RequiresPermissions("system:template:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ZknjExpTemplate zknjExpTemplate)
    {
        startPage();
        List<ZknjExpTemplate> list = zknjExpTemplateService.selectZknjExpTemplateList(zknjExpTemplate);
        return getDataTable(list);
    }

    /**
     * 新增模板
     */
    @GetMapping("/add/{instId}")
    public String add(@PathVariable("instId") Long instId, ModelMap mmap)
    {
        //判断仪器状态，审核已通过的才允许操作
        if(instrumentService.selectZkInstrumentByInstId(instId).getStatus() != 0){
            return prefix + "/error";
        }
        mmap.addAttribute("instId", instId);
        return prefix + "/add";
    }

    /**
     * 新增保存模板
     */
    @RequiresPermissions("system:template:add")
    @Audit(businessTitle = BusinessTitle.INSTRUMENT, businessAction = BusinessAction.CREATED, description = "新增模板")
    @PostMapping("/uploads/{instId}")
    @ResponseBody
    public AjaxResult uploadFiles(List<MultipartFile> files, @PathVariable("instId") Long instId) throws Exception
    {
        logger.debug("上传模板文件: " + files.size() + " 个");
        try
        {
            // 上传文件路径
            String filePath = GxPConfig.getTemplatePath();
            String instName = instrumentService.selectZkInstrumentByInstId(instId).getInstName();
            for (MultipartFile file : files)
            {
                // 上传到指定位置，并返回文件名称（不带后缀）
                String fileName = FileUploadUtils.upload2data(filePath+"/"+instName, file);
                //解析文件，输出autopara.xml文件内容
                String path = GxPConfig.getTemplatePath() + "/" + instName +"/" + fileName +".jar";
                JarFile jarFile = new JarFile(path);
                JarEntry jarEntry = null;

                Enumeration<JarEntry> entries = jarFile.entries();
                while (entries.hasMoreElements()) {
                    JarEntry entry = entries.nextElement();
                    if (!entry.isDirectory() && entry.getName().endsWith("autopara.xml")) {
                        jarEntry = entry;
                        break;
                    }
                }
                if(jarEntry == null){
                    logger.error("上传模板文件错误，没有找到autopara.xml文件: " + file.getOriginalFilename());
                    continue;
                }
                InputStream is = jarFile.getInputStream(jarEntry);
                String value = new BufferedReader(new InputStreamReader(is))
                        .lines().collect(Collectors.joining(System.lineSeparator()));
                //添加template数据库
                ZknjExpTemplate template = new ZknjExpTemplate();
                template.setTemName(fileName);
                template.setInstId(instId);
                List<ZknjExpTemplate> templates = zknjExpTemplateService.selectZknjExpTemplateList(template);
                logger.debug(templates == null || templates.isEmpty() ? "添加模板: " + file.getOriginalFilename() : "更新模板: " + file.getOriginalFilename());
                if(templates == null || templates.isEmpty()){
                    //添加template
                    template.setTemPara(value);
                    template.setTemStatus(0);
                    zknjExpTemplateService.insertZknjExpTemplate(template);
                }else if(templates.size() == 1){
                    //更新参数集
                    ZknjExpTemplate zknjExpTemplate = new ZknjExpTemplate();
                    zknjExpTemplate.setTemId(templates.get(0).getTemId());
                    zknjExpTemplate.setTemPara(value);
                    zknjExpTemplateService.updateZknjExpTemplate(zknjExpTemplate);
                }
            }

            AjaxResult ajax = AjaxResult.success();
            return ajax;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 修改模板
     */
    @RequiresPermissions("system:template:edit")
    @GetMapping("/edit/{temId}")
    public String edit(@PathVariable("temId") Long temId, ModelMap mmap)
    {
        ZknjExpTemplate zknjExpTemplate = zknjExpTemplateService.selectZknjExpTemplateByTemId(temId);
        mmap.put("zknjExpTemplate", zknjExpTemplate);
        return prefix + "/edit";
    }

    /**
     * 修改保存模板
     */
    @RequiresPermissions("system:template:edit")
    @Audit(businessTitle = BusinessTitle.INSTRUMENT, businessAction = BusinessAction.UPDATED, description = "模板修改")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ZknjExpTemplate zknjExpTemplate)
    {
        return toAjax(zknjExpTemplateService.updateZknjExpTemplate(zknjExpTemplate));
    }

    /**
     * 删除模板
     */
    @RequiresPermissions("system:template:remove")
    @Audit(businessTitle = BusinessTitle.INSTRUMENT, businessAction = BusinessAction.DELETED, description = "模板删除")
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(zknjExpTemplateService.deleteZknjExpTemplateByTemIds(ids));
    }

    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(ZknjExpTemplate template){
        return toAjax(zknjExpTemplateService.changeStatus(template));
    }
}
